﻿using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Orchard;
using Orchard.Media.Services;
using Orchard.Environment.Extensions;
using Orchard.ContentManagement.MetaData;
using FruitCake.SimpleGallery.Models;

namespace FruitCake.SimpleGallery.Services
{
    public interface ISimpleGalleryService : IDependency
    {

        bool IsPathValid(string path);

        IEnumerable<SimpleGalleryImage> GetImages(SimpleGalleryPart part);

    }

    [OrchardFeature("FruitCake.SimpleGallery")]
    public class SimpleGalleryService : ISimpleGalleryService
    {

        private readonly IContentDefinitionManager _contentDefinitionManager;
        private readonly IMediaService _mediaService;

        public SimpleGalleryService(
            IContentDefinitionManager contentDefinitionManager,
            IMediaService mediaService)
        {

            _contentDefinitionManager = contentDefinitionManager;
            _mediaService = mediaService;
        }

        public bool IsPathValid(string path)
        {
            return String.IsNullOrWhiteSpace(path) || Regex.IsMatch(path, @"^[^:?#\[\]@!$&'()*+,;=\s\""\<\>\\]+$") && !(path.StartsWith(".") || path.EndsWith("."));
        }

        public IEnumerable<SimpleGalleryImage> GetImages(SimpleGalleryPart part)
        {
            List<SimpleGalleryImage> images = new List<SimpleGalleryImage>();

            if (part.Path == null) return images;

            var folderPath = part.Path.Replace('/', Path.DirectorySeparatorChar);
            var parentFolder = Path.GetDirectoryName(folderPath);
            var folderName = Path.GetFileName(folderPath);

            if (_mediaService.GetMediaFolders(parentFolder).All(f => f.Name != folderName))
            {
                _mediaService.CreateFolder(parentFolder, folderName);
                return images;
            }

            // Thumbnail?
            string thumbnailFolder = null;
            if (part.EnableThumbnail)
            {
                thumbnailFolder = Path.Combine(folderPath, "Thumbnail");
            }

            // Available files
            IEnumerable<string> imgPaths = _mediaService
                .GetMediaFiles(folderPath)
                .OrderBy(p => p.Name)
                .Select(p => _mediaService.GetPublicUrl(part.Path + "/" + p.Name))
                .ToList();

            // Images...
            foreach (string imgPath in imgPaths)
            {
                // ToDo: check supported extensions

                string imgName = Path.GetFileNameWithoutExtension(imgPath);
                string imgTitle = imgName;

                if (part.HasTitleSeparator)
                {
                    int pos = imgName.IndexOf(part.TitleSeparator);
                    if(pos>=0)
                    {                        
                        imgName = imgName.Substring(0,pos);
                        imgTitle = imgTitle.Substring(pos+1);
                    }                    
                }
                
                SimpleGalleryImage img = new SimpleGalleryImage();
                img.Name = imgName;
                img.Title = imgTitle;
                img.FilePath = imgPath;

                if (part.EnableThumbnail)
                {
                    string thumbnailPath = _mediaService.GetMediaPublicUrl(thumbnailFolder, Path.GetFileName(imgPath));
                    if(File.Exists(System.Web.Hosting.HostingEnvironment.MapPath(thumbnailPath))) 
                        img.ThumbnailPath = thumbnailPath;        
                }
                

                // ToDo: get image size?

                images.Add(img);
            }

            return images;
        }
    }
}